package parkshop.pmcourse.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.ObjectMapper;

import parkshop.pmcourse.service.FileUploadService;
import parkshop.pmcourse.utils.FileTools;

@Controller
public class FileCtrl {
	
	@Autowired
	private FileUploadService fileService;
	
	
	@PostMapping("/product/image/put")
	public void putProductImage(HttpServletRequest request, Model model, PrintWriter out){
		
		String picUrl=fileService.uploadPic(request);	
		out.write(picUrl);
	}
	
	
	 @GetMapping("/image/get/{fileName}")
	 public void getImage(@PathVariable("fileName")String fileName,HttpServletRequest request,HttpServletResponse response){
		// fileName 是图片的名称.
		 fileName=FileTools.recoverDot(fileName);// 路径中   . 会丢失,事先替换掉了.参考 FileUploadService
		 String suffix =FileTools.getSuffix(fileName);
		 FileInputStream fis = null;
		 response.setContentType("image/"+suffix);
		 response.setCharacterEncoding("utf-8");
		    try {
		        OutputStream out = response.getOutputStream();
		        File file = new File(FileTools.getFilePath(suffix)+File.separatorChar+fileName);
		        fis = new FileInputStream(file);
		        byte[] b = new byte[fis.available()];
		        fis.read(b);
		        out.write(b);
		        out.flush();
		    } catch (Exception e) {
		         e.printStackTrace();
		    } finally {
		        if (fis != null) {
		            try {
		               fis.close();
		            } catch (IOException e) {
			        e.printStackTrace();
			    }   
		          }
		    } 
	 }

}
